package com.zhiwang.planet.mvvm.viewmodel.my

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableBoolean
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.zhiwang.planet.R
import me.tatarka.bindingcollectionadapter2.ItemBinding
import com.zhiwang.planet.BR
import com.zhiwang.planet.event.AvatarChangeEvent
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.util.*
import io.reactivex.functions.Action
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject


class AvatarItemViewModel constructor(var selected: ObservableBoolean, var url: String,var id:String, var index: Int, var onSelected: (Int) -> Unit) {


    fun onSelected() {
        onSelected.invoke(index)
    }
}


class ChangeAvatarViewModel @Inject constructor(val restApi: RestApi, var context: AppCompatActivity) : ViewModel() {


    var selectedIndex = -1
    val itemBinding = ItemBinding.of<AvatarItemViewModel>(BR.avatarItemVm, R.layout.item_avatar)

    val itemDatas = MutableLiveData<List<AvatarItemViewModel>>()

    @SuppressLint("CheckResult")
    fun load() {
        restApi.getAvatarList()
                .androidSchedule()
                .responseFunc()
                .subscribe({

                    itemDatas.value = it.mapIndexed { index, t -> AvatarItemViewModel(ObservableBoolean(false), t.avatar_url,t.id, index, onSelected = ::onSelected) }
                },{

                })


    }

    fun onSelected(pos: Int) {
        selectedIndex = pos
        itemDatas.value?.forEachIndexed { index, avatarItemViewModel ->
            avatarItemViewModel.selected.set(index == pos)
        }
    }


    fun changeAvatar() {

        if (selectedIndex == -1) {
            Toaster.message("请先选择头像")
            return
        }

        itemDatas.value?.get(selectedIndex)?.let {
            restApi.changeAvatar(it.id)
                    .arrangeComplete(Action {
                        EventBus.getDefault().post(AvatarChangeEvent())
                        Toaster.message("修改头像成功")
                        context.suicideAfterTransition()
                    }, { })
        }
    }

}